﻿FUNCTION DetectAnomalies(dataFilePath, featuresWeights, it, rank)
    // Initialize ML Context
    context = NEW MLContext()

    // Load and preprocess data
    data = EMPTY LIST
    FOR EACH line IN File.ReadAllLines(dataFilePath) DO
        parts = Split(line, '\t', RemoveEmptyEntries)
        IF Length(parts) == 9 THEN
            // Compute weighted mean for the entire row
            weightedValues = EMPTY LIST
            FOR i FROM 0 TO Length(parts) - 1 DO
                value = ParseFloat(parts[i], CultureInfo.InvariantCulture)
                weight = featuresWeights[i]
                weightedValues.ADD(value * weight)
            END FOR
            lineWeightedMean = Sum(weightedValues) / Sum(featuresWeights)
            data.ADD(New DataPoint { Features = [lineWeightedMean] })
        ELSE
            THROW ArgumentException("Wrong dimension!")
        END IF
    END FOR

    // Convert data to DataView
    dataView = context.Data.LoadFromEnumerable(data)

    // Algorithm 1: PCA Anomaly Detection
    pcaPipeline = context.AnomalyDetection.Trainers.RandomizedPca(
        featureColumnName = "Features",
        rank = rank,
        exampleWeightColumnName = NULL,
        seed = 1,
        ensureZeroMean = TRUE)
    pcaModel = pcaPipeline.Fit(dataView)
    pcaPredictions = pcaModel.Transform(dataView)
    pcaResults = context.Data.CreateEnumerable<AnomalyPrediction>(pcaPredictions, reuseRowObject = FALSE).ToList()

    PRINT("RandomizedPCA (" + it + " entry):")
    cnt1 = 0, cnt2 = 0, cnt3 = 0, cnt4 = 0
    FOR i FROM 0 TO Length(pcaResults) - 1 DO
        IF i < 400 THEN
            IF pcaResults[i].PredictedLabel == FALSE THEN
                cnt1 = cnt1 + 1
            ELSE
                cnt2 = cnt2 + 1
            END IF
        ELSE
            IF pcaResults[i].PredictedLabel == TRUE THEN
                cnt3 = cnt3 + 1
            ELSE
                cnt4 = cnt4 + 1
            END IF
        END IF
    END FOR
    PRINT(cnt1 + " vs. " + cnt2)
    PRINT(cnt3 + " vs. " + cnt4)

    Reset counters: cnt1 = 0, cnt2 = 0, cnt3 = 0, cnt4 = 0

    // Algorithm 2: K-Means Clustering Anomaly Detection
    kMeansPipeline = context.Clustering.Trainers.KMeans(
        featureColumnName = "Features",
        numberOfClusters = 2)
    kMeansModel = kMeansPipeline.Fit(dataView)
    kMeansPredictions = kMeansModel.Transform(dataView)
    kMeansResults = context.Data.CreateEnumerable<ClusterPrediction>(kMeansPredictions, reuseRowObject = FALSE).ToList()

    PRINT("K-Means Clustering (" + it + " entry):")
    FOR i FROM 0 TO Length(kMeansResults) - 1 DO
        IF i < 400 THEN
            IF kMeansResults[i].PredictedClusterId == 1 THEN
                cnt1 = cnt1 + 1
            ELSE
                cnt2 = cnt2 + 1
            END IF
        ELSE
            IF kMeansResults[i].PredictedClusterId == 1 THEN
                cnt3 = cnt3 + 1
            ELSE
                cnt4 = cnt4 + 1
            END IF
        END IF
    END FOR
    PRINT(cnt1 + " vs. " + cnt2)
    PRINT(cnt3 + " vs. " + cnt4)
END FUNCTION